package com.ai.common.util;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

/**
 * @author daizy
 * 
 *         java 压缩 解压缩工具类
 * 
 *         2015/06/16
 * 
 */
public class ZipUtils {

	private final static Log logger = LogFactory.getLog(ZipUtils.class);

	/**
	 * 压缩文件
	 * 
	 * @param srcPathName
	 *            来源目录
	 * @param zipPathName
	 *            生成文件路径 +"zxHtml//publish_1.zip"
	 */
	public static void compress(String srcPathName, String zipPathName,boolean isMustDel) {
		File srcdir = new File(srcPathName);
		if (!srcdir.exists()) {
			srcdir.mkdirs();
		}
		Project prj = new Project();
		Zip zip = new Zip();
		zip.setProject(prj);
		zip.setDestFile(new File(zipPathName));
		FileSet fileSet = new FileSet();
		fileSet.setProject(prj);
		fileSet.setDir(srcdir);
		// fileSet.setIncludes("*.html"); //包括哪些文件或文件夹
		fileSet.setExcludes("*.zip"); // 排除哪些文件或文件夹
		zip.addFileset(fileSet);
		zip.execute();
		if(isMustDel){
			// 删除本地文件
			delFolder(srcPathName);
		}
	}

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	public static void main(String[] args) {
		String srcPathName = "F:/daizhaoyun/selfSpace/info-backend/info-backend-server/src/main/webapp/statics/zxHtml/aaa";
		String zipPath = "F:/daizhaoyun/selfSpace/info-backend/info-backend-server/src/main/webapp/statics/zxHtml/";
		//ZipUtils.compress(srcPathName, zipPath, "20140901",false);
	}

}
